<template>
  <div class="msg-box">
    <span>{{ errorMsg.msg }}</span>
    <div class="login-box" v-if="dataLoading">
      <span>
        <van-loading size="24px" type="spinner" vertical>加载中...</van-loading>
      </span>
    </div>
  </div>
</template>
<script setup>
import { appid, wwwUrl } from "@/utils/constant";
import { computed, reactive, toRefs, ref, onMounted } from "vue"
import { useRoute, useRouter } from "vue-router"

import userOrderStore from "@/store/index.js"

import {
  BindMemberCode
} from "@/api/mine/index.js"

import { getOpenid, getJspToken, GetUserInfo } from "@/api/common.js";
let { setUserInfo, getIsPageLoading, setIsPageLoading } = userOrderStore()

const route = useRoute()
const router = useRouter()

const state = reactive({

})
let errorMsg = ref("")
let dataLoading = ref(true)
const getOpenidFn = async () => {
  //先判断有没有授权(判断地址栏code，有就-用户同意了授权，没有-没授权或者拒绝授权)
  // let str = route.query.code; //此处使用的是history路由模式，hash这么拿不到。
  let _params = queryURLParams(window.location.href);
  if (_params.code) {
    // 走后端接口(把code传给后台，让后台根据code获取openID与用户信息)
    let params = {
      code: _params.code,
    };
    // setIsPageLoading(true)
    let { data } = await getOpenid(params);
    if (data.openId) {
      let userInfo = await GetUserInfo({
        openId: data.openId
      })
      setUserInfo(userInfo.data)
      localStorage.setItem("openid", data.openId);
      //拿到了ACCESS_TOKEN与用户openid，跳转到登录页面
      let jspParams = {
        url: window.location.href,
      };
      console.log(jspParams, "jspParams");
      try {
        let dataJsp = await getJspToken(jspParams);
        if (route.query.code) {
          // 绑定会员码secretToken
          let openId = localStorage.getItem('openid')
          try {
            let dataCode = await BindMemberCode({
              openId,
              token: route.query.secretToken
            })
            dataLoading.value = false
            console.log(dataCode, 'dataCode')
            router.push({
              path: "/mine"
            })
            setIsPageLoading(false)
          } catch (error) {
            errorMsg.value = error
            setIsPageLoading(false)
            console.log(error)
            dataLoading.value = false
          }
          // if (dataCode) {
          //   showToast("主播绑定成功！")
          //   router.push({
          //     path:'/mine'
          //   })
          // }
        }
        // console.log(dataJsp, "data token");
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appid, // 必填，公众号的唯一标识
          timestamp: dataJsp.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: dataJsp.data.nonceStr, // 必填，生成签名的随机串
          signature: dataJsp.data.signature, // 必填，签名
          jsApiList: ["checkJsApi", "chooseWXPay"], // 必填，需要使用的JS接口列表
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: ["chooseWXPay"],
            success: (res) => {
              console.log("checked api:", res);
            },
            fail: (err) => {
              console.log("check api fail:", err);
            },
          });
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        });

        return;
      } catch (error) { }
      // getOpenid(params)
      //   .then(async (res) => {
      //       console.log(res,'res')
    } else {
      // window.location.href = wwwUrl
    }
  }
};
const queryURLParams = (URL) => {
  let url = URL.split("?")[1];
  const urlSearchParams = new URLSearchParams(url);
  const params = Object.fromEntries(urlSearchParams.entries());
  return params;
};

const getCode = () => {
  //没授权先授权,授权后会有一个code在地址栏上
  let params = queryURLParams(window.location.href);
  if (params.code) {
    let _code = localStorage.getItem("code")
    // console.log(_code != params.code, '996')
    if (_code != params.code) {
      localStorage.setItem("code", params.code);
      getOpenidFn();
    }
    return;
  }
  // return 
  window.location.href =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    encodeURIComponent(window.location.href) +
    "&response_type=code&connect_redirect=1&scope=snsapi_base&state=state#wechat_redirect";
};
const isWeixinBrowser = () => {
  let ua = navigator.userAgent.toLowerCase();
  return /micromessenger/.test(ua) ? true : false;
}

// 微信环境获取code
if (isWeixinBrowser()) {
  getCode()
}

onMounted(async () => {

})

</script>



<style lang="scss" scoped>
.msg-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}
.login-box{
  width: 100vw;
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  span{
    padding:15px;
    background: #fff;
    border-radius: 8px;
  }
}
</style>
